/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.IllegalOrphanException;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Card;
import shmallarchitect.jpa.entities.Resource;
import java.util.HashSet;
import java.util.Set;
import shmallarchitect.jpa.entities.Locum;
import java.util.ArrayList;

/**
 *
 * @author jaccus
 */
public class CardJpaController {
    @javax.annotation.Resource (mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Card card) throws RollbackFailureException, Exception {
        if (card.getResources() == null) {
            card.setResources(new HashSet<Resource>());
        }
        if (card.getLocums() == null) {
            card.setLocums(new HashSet<Locum>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Set<Resource> attachedResources = new HashSet<Resource>();
            for (Resource resourcesResourceToAttach : card.getResources()) {
                resourcesResourceToAttach = em.getReference(resourcesResourceToAttach.getClass(), resourcesResourceToAttach.getId());
                attachedResources.add(resourcesResourceToAttach);
            }
            card.setResources(attachedResources);
            Set<Locum> attachedLocums = new HashSet<Locum>();
            for (Locum locumsLocumToAttach : card.getLocums()) {
                locumsLocumToAttach = em.getReference(locumsLocumToAttach.getClass(), locumsLocumToAttach.getId());
                attachedLocums.add(locumsLocumToAttach);
            }
            card.setLocums(attachedLocums);
            em.persist(card);
            for (Resource resourcesResource : card.getResources()) {
                resourcesResource.getCards().add(card);
                resourcesResource = em.merge(resourcesResource);
            }
            for (Locum locumsLocum : card.getLocums()) {
                Card oldCardOfLocumsLocum = locumsLocum.getCard();
                locumsLocum.setCard(card);
                locumsLocum = em.merge(locumsLocum);
                if (oldCardOfLocumsLocum != null) {
                    oldCardOfLocumsLocum.getLocums().remove(locumsLocum);
                    oldCardOfLocumsLocum = em.merge(oldCardOfLocumsLocum);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Card card) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Card persistentCard = em.find(Card.class, card.getId());
            Set<Resource> resourcesOld = persistentCard.getResources();
            Set<Resource> resourcesNew = card.getResources();
            Set<Locum> locumsOld = persistentCard.getLocums();
            Set<Locum> locumsNew = card.getLocums();
            List<String> illegalOrphanMessages = null;
            for (Locum locumsOldLocum : locumsOld) {
                if (!locumsNew.contains(locumsOldLocum)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Locum " + locumsOldLocum + " since its card field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Set<Resource> attachedResourcesNew = new HashSet<Resource>();
            for (Resource resourcesNewResourceToAttach : resourcesNew) {
                resourcesNewResourceToAttach = em.getReference(resourcesNewResourceToAttach.getClass(), resourcesNewResourceToAttach.getId());
                attachedResourcesNew.add(resourcesNewResourceToAttach);
            }
            resourcesNew = attachedResourcesNew;
            card.setResources(resourcesNew);
            Set<Locum> attachedLocumsNew = new HashSet<Locum>();
            for (Locum locumsNewLocumToAttach : locumsNew) {
                locumsNewLocumToAttach = em.getReference(locumsNewLocumToAttach.getClass(), locumsNewLocumToAttach.getId());
                attachedLocumsNew.add(locumsNewLocumToAttach);
            }
            locumsNew = attachedLocumsNew;
            card.setLocums(locumsNew);
            card = em.merge(card);
            for (Resource resourcesOldResource : resourcesOld) {
                if (!resourcesNew.contains(resourcesOldResource)) {
                    resourcesOldResource.getCards().remove(card);
                    resourcesOldResource = em.merge(resourcesOldResource);
                }
            }
            for (Resource resourcesNewResource : resourcesNew) {
                if (!resourcesOld.contains(resourcesNewResource)) {
                    resourcesNewResource.getCards().add(card);
                    resourcesNewResource = em.merge(resourcesNewResource);
                }
            }
            for (Locum locumsNewLocum : locumsNew) {
                if (!locumsOld.contains(locumsNewLocum)) {
                    Card oldCardOfLocumsNewLocum = locumsNewLocum.getCard();
                    locumsNewLocum.setCard(card);
                    locumsNewLocum = em.merge(locumsNewLocum);
                    if (oldCardOfLocumsNewLocum != null && !oldCardOfLocumsNewLocum.equals(card)) {
                        oldCardOfLocumsNewLocum.getLocums().remove(locumsNewLocum);
                        oldCardOfLocumsNewLocum = em.merge(oldCardOfLocumsNewLocum);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = card.getId();
                if (findCard(id) == null) {
                    throw new NonexistentEntityException("The card with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Card card;
            try {
                card = em.getReference(Card.class, id);
                card.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The card with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Set<Locum> locumsOrphanCheck = card.getLocums();
            for (Locum locumsOrphanCheckLocum : locumsOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Card (" + card + ") cannot be destroyed since the Locum " + locumsOrphanCheckLocum + " in its locums field has a non-nullable card field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Set<Resource> resources = card.getResources();
            for (Resource resourcesResource : resources) {
                resourcesResource.getCards().remove(card);
                resourcesResource = em.merge(resourcesResource);
            }
            em.remove(card);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Card> findCardEntities() {
        return findCardEntities(true, -1, -1);
    }

    public List<Card> findCardEntities(int maxResults, int firstResult) {
        return findCardEntities(false, maxResults, firstResult);
    }

    private List<Card> findCardEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Card as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Card findCard(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Card.class, id);
        } finally {
            em.close();
        }
    }

    public int getCardCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Card as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
